package org.flint.data.structure.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * @author flint92
 */
public class IntersectionOfTwoArrays {

    /**
     * Given two arrays, write a function to compute their intersection.
     * <p>
     * Example 1:
     * <p>
     * Input: nums1 = [1,2,2,1], nums2 = [2,2]
     * Output: [2]
     * Example 2:
     * <p>
     * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
     * Output: [9,4]
     * Note:
     * <p>
     * Each element in the result must be unique.
     * The result can be in any order.
     *
     * @param nums1     数组1
     * @param nums2     数组2
     * @return          交集
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0
                || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> s1 = intArrayToSet(nums1);
        Set<Integer> s2 = intArrayToSet(nums2);
        s1.retainAll(s2);
        return intSetToArray(s1);
    }

    private int[] intSetToArray(Set<Integer> set) {
        int[] a = new int[set.size()];
        int i = 0;
        for (Integer s : set) {
            a[i++] = s;
        }
        return a;
    }

    private Set<Integer> intArrayToSet(int[] array) {
        Set<Integer> set = new HashSet<>();
        for (int a : array) {
            set.add(a);
        }
        return set;
    }
}
